package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginSuccessVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author DELL
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-12-15 10:20:03
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{
    @Autowired
    private StringRedisTemplate  redisTemplate;

    @Override
    public LoginSuccessVo login(UserInfo userInfo) {
        LoginSuccessVo resp =new LoginSuccessVo();
        //去数据库中查询该数据
        String loginName = userInfo.getLoginName();
        String passwd = MD5.encrypt(userInfo.getPasswd());
        UserInfo info = lambdaQuery().eq(UserInfo::getLoginName, loginName)
                .eq(UserInfo::getPasswd, passwd)
                .one();

       if(info==null){
           throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
       }
      //登录成功生成一个令牌
        String token = UUID.randomUUID().toString().replace("-", "");

        resp.setToken(token);
        resp.setUserId(info.getId());
        resp.setNickName(info.getNickName());
        //服务端共享token与用户信息相对应  存储到redis中、
        //TODO 登录时间太短  12秒后读取不到数据
        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER +token, JSON.toJSONString(info),7, TimeUnit.DAYS  );
        //给前端返回数据
        return resp;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER+token);
    }
}




